import { message } from 'antd'
import { push, RouterAction } from 'react-router-redux'
import router from '../../../../router'


import * as TYPES from './constants';
import { login } from '../../../../services/account'
import { getUserRole } from '../../../../services/permission'
import { formData } from '../../mark'
import storage from '../../../../utils/storage'

const { session } = storage

const toLogin = (requestData: formData) => {


    return async (dispatch: (arg0: RouterAction | object) => void) => {
        const res: any = await login(requestData)
        const { resCode, data } = res;
        session?.set?.('token', data.token)
        session?.set?.('userData', data)
        try {
            if (resCode === 0) {
                // 登录成功后跳转到首页
                dispatch(push('/index'))
            }
            message.success(res.message);
        } catch (error) {
            message.warn("登录失败");
        }

        dispatch({
            type: TYPES.LOGIN,
            payload: data
        })
    }
}

const toLogout = () => {
    return (dispatch: (arg0: RouterAction | object) => void) => {

        session?.remove?.('token');
        session?.remove?.('userData');
        dispatch({
            type: TYPES.LOGOUT
        })
        dispatch(push('/'))
    }
}

// 掉接口获取-当前用户的角色权限
const getUserRoles = async () => {
    return {
        type: TYPES.ROUTE_ARY,
        payload: await getUserRole({}).then((res: any) => {
            return handleRoutes(res.data.role)
        })
    }
}

// 通过接口方式-过滤路由 
const handleRoutes = (params: any) => {
    const userRole = params && params.split(",");
    //   // 存储路由 
    let routers = []
    // // 如果userRole包含admin--超级管理员 就全部展示 
    if (userRole.includes('admin')) {
        routers = router
    } else {
        // 其它的 过滤
        routers = router.filter((item: any) => {
            if (hasPermission(item, userRole)) {
                // 如果有子级的话
                if (item.child && item.child.length > 0) {
                    item.child = item.child.filter((child: any) => {
                        if (hasPermission(child, userRole)) {
                            return child
                        }
                        return child
                    })
                }
                return item
            }
            return item
        })
    }
    return routers
}
// 方法 
// 过滤函数 -- 便于子级递归过滤 
const hasPermission = (item: any, router: any) => {
    if (item.role && item.role.length > 0) {
        return router.some((elem: any) => item.role.indexOf(elem) >= 0);
    }
}



export { toLogin, toLogout, getUserRoles }